<?php
declare(strict_types=1);
/**
 * 七牛上传文件服务
 */
namespace Service\FileService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssModel\Sysconfig;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
class QiniuFileService extends BaseService
{
    /**
     * 上传文件服务
     * @param string $file
     */
    public function uploadFile(array $config,string $file)
    {
        $config = Sysconfig::instance()->getConfigByEventsValue($config['oss_way']);
        if( empty($config) ) {
            return Normal::returnCode(Normal::FAIL,"上传三方配置文件不存在!");
        }
        $accessKey = $config['AccessKey'];
        $secretKey = $config['SecretKey'];
        $bucket    = $config['bucket'];
        
        $pathinfo = pathinfo($file);
        if(empty($pathinfo['extension']) ) {
            return Normal::returnCode(Normal::FAIL,"上传文件扩展配置不正确!");
        }
        
        $_new_file_name = md5($file).".".$pathinfo['extension'];
        $token     = $this->getQiniuYunToken($config);
        $uploadMgr = new UploadManager();
        list($ret, $error) = $uploadMgr->putFile($token,$_new_file_name,$file);
        if( !empty($error) ) {
            $msg = json_encode($error,JSON_UNESCAPED_UNICODE);
            return Normal::returnCode(Normal::FAIL,"上传文件出现错误：{$msg}");
        }
        
        return Normal::returnCode(Normal::SUC,"上传成功",[
            'url'  => $config['upLoadURL'].'/'.$_new_file_name,
        ]);
    }
    
    /**
     * 获取七牛云token
     * @param array $oss_config
     */
    public function getQiniuYunToken(array $oss_config)
    {
        $auth = new Auth($oss_config['AccessKey'], $oss_config['SecretKey']);
        // 生成上传Token
        $token = $auth->uploadToken($oss_config['bucket']);
        return $token;
    }
}